package com.cloudlinkscm.base.filecenter.domain.filesystem;

import com.cloudlinkscm.base.filecenter.domain.AbstractFileRecordManager;
import com.cloudlinkscm.base.filecenter.domain.AbstractFileStorage;
import com.cloudlinkscm.base.filecenter.domain.FileStreamManager;
import com.cloudlinkscm.base.filecenter.domain.SysAuthCodeManager;
import com.cloudlinkscm.base.filecenter.exception.*;
import com.cloudlinkscm.base.filecenter.model.FileStream;
import com.cloudlinkscm.base.filecenter.model.SysAuthCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @author : tac
 * @date : 2017/7/24
 */
@Component
public class FileSystemStorage extends AbstractFileStorage {
    @Autowired
    public FileSystemStorage(SysAuthCodeManager sysAuthCodeManager, AbstractFileRecordManager fileRecordManager, FileStreamManager fileStreamManager) {
        super(sysAuthCodeManager, fileRecordManager, fileStreamManager);
    }

    @Override
    protected String store(MultipartFile file, String sysCode, String relativeLocation) {
        SysAuthCode auth = sysAuthCodeManager.dao.getBySysCode(sysCode);
        if(auth == null){
            throw new NotAuthorizedException(sysCode);
        }

        String storedLocation = buildStoredLocation(relativeLocation, auth);
        File f = new File(storedLocation);
        try {
            file.transferTo(f);
        } catch (IOException e) {
            logger.error("文件存储失败", e);
            throw new FileSaveException();
        }
        return storedLocation;
    }

    @Override
    protected void remove(String sysCode, String relativePath) {
        String path = Paths.get(sysAuthCodeManager.dao.getBySysCode(sysCode).getBaseLocation(), relativePath).toString();
        File file = new File(path);
        if(file.exists()){
            file.delete();
        }else{
            logger.warn("文件" + path + "不存在");
        }
    }

    @Override
    protected String buildStoredLocation(String storedName, SysAuthCode auth) {
        File folder = new File(auth.getBaseLocation());
        if(!folder.exists()){
            folder.mkdir();
        }
        return auth.getBaseLocation() + "\\" + storedName;
    }

    @Override
    public InputStream getFileInputStream(FileStream stream) {
        if (fileStreamManager.isExpired(stream)) {
            throw new FileStreamExpiredException();
        }
        File file = new File(stream.getFileLocation());

        try {
            return new FileInputStream(file);
        } catch (FileNotFoundException e) {
            logger.warn("文件" + stream.getFileLocation() + "不存在", e);
            throw new FileNotExistException();
        }
    }

}
